package com.example.controller;

import com.example.service.LaundryOrderService;
import com.example.repository.UserRepository;
import com.example.repository.EquipmentRepository;
import com.example.repository.InventoryRepository;
import com.example.repository.IncomeRepository;
import com.example.repository.ExpenseRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@Tag(name = "统计报表", description = "各种统计数据和图表")
public class StatisticsController {
    
    @Autowired
    private LaundryOrderService laundryOrderService;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private EquipmentRepository equipmentRepository;
    
    @Autowired
    private InventoryRepository inventoryRepository;
    
    @Autowired
    private IncomeRepository incomeRepository;
    
    @Autowired
    private ExpenseRepository expenseRepository;

    // ==================== 洗护统计 ====================
    @GetMapping("/wash/statistics/revenue-chart")
    @Operation(summary = "获取洗护收入图表")
    public ResponseEntity<Map<String, Object>> getWashRevenueChart(
            @RequestParam(required = false) String period,
            @RequestParam(required = false) Integer days) {
        
        Map<String, Object> chartData = new HashMap<>();
        
        // 获取收入趋势数据
        LocalDateTime twelveMonthsAgo = LocalDateTime.now().minusMonths(12);
        List<Object[]> monthlyStats = incomeRepository.getMonthlyIncomeStats(twelveMonthsAgo);
        chartData.put("monthlyRevenue", monthlyStats);
        
        // 总收入
        BigDecimal totalRevenue = incomeRepository.getTotalIncome();
        chartData.put("totalRevenue", totalRevenue != null ? totalRevenue : BigDecimal.ZERO);
        
        // 今日收入
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        BigDecimal todayRevenue = incomeRepository.getTodayIncome(startOfDay, endOfDay);
        chartData.put("todayRevenue", todayRevenue != null ? todayRevenue : BigDecimal.ZERO);
        
        // 本月收入
        BigDecimal monthlyRevenue = incomeRepository.getMonthlyIncome();
        chartData.put("currentMonthRevenue", monthlyRevenue != null ? monthlyRevenue : BigDecimal.ZERO);
        
        return ResponseEntity.ok(chartData);
    }

    @GetMapping("/wash/statistics/service-chart")
    @Operation(summary = "获取洗护服务图表")
    public ResponseEntity<Map<String, Object>> getWashServiceChart(
            @RequestParam(required = false) String period) {
        
        Map<String, Object> chartData = new HashMap<>();
        
        // 这里应该统计各种服务的使用情况
        // 暂时返回示例数据
        chartData.put("serviceUsage", List.of(
            Map.of("serviceName", "干洗", "count", 150, "percentage", 35.0),
            Map.of("serviceName", "水洗", "count", 200, "percentage", 47.0),
            Map.of("serviceName", "熨烫", "count", 50, "percentage", 12.0),
            Map.of("serviceName", "特殊护理", "count", 25, "percentage", 6.0)
        ));
        
        return ResponseEntity.ok(chartData);
    }

    @GetMapping("/wash/statistics/equipment-chart")
    @Operation(summary = "获取洗护设备图表")
    public ResponseEntity<Map<String, Object>> getWashEquipmentChart(
            @RequestParam(required = false) String period) {
        
        Map<String, Object> chartData = new HashMap<>();
        
        // 设备状态统计
        List<Object[]> statusStats = equipmentRepository.countByStatus();
        chartData.put("equipmentStatus", statusStats);
        
        // 设备类型统计
        List<Object[]> typeStats = equipmentRepository.countByType();
        chartData.put("equipmentTypes", typeStats);
        
        // 总设备数
        long totalEquipment = equipmentRepository.count();
        chartData.put("totalEquipment", totalEquipment);
        
        return ResponseEntity.ok(chartData);
    }

    // ==================== 商家端统计 ====================
    @GetMapping("/merchant/dashboard/statistics")
    @Operation(summary = "获取商家仪表板统计数据")
    public ResponseEntity<Map<String, Object>> getMerchantDashboardStatistics() {
        Map<String, Object> dashboard = new HashMap<>();
        
        // 订单统计
        LaundryOrderService.OrderStatistics orderStats = laundryOrderService.getOrderStatistics();
        dashboard.put("totalOrders", orderStats.getTotalOrders());
        dashboard.put("todayOrders", orderStats.getTodayOrders());
        dashboard.put("pendingOrders", orderStats.getPendingOrders());
        dashboard.put("todayRevenue", orderStats.getTodayRevenue());
        
        // 用户统计
        long totalUsers = userRepository.count();
        dashboard.put("totalUsers", totalUsers);
        
        // 设备统计
        long totalEquipment = equipmentRepository.count();
        dashboard.put("totalEquipment", totalEquipment);
        
        // 库存统计
        Long lowStockCount = inventoryRepository.countLowStockItems();
        dashboard.put("lowStockItems", lowStockCount);
        
        return ResponseEntity.ok(dashboard);
    }

    @GetMapping("/merchant/orders/statistics")
    @Operation(summary = "获取商家订单统计")
    public ResponseEntity<Map<String, Object>> getMerchantOrdersStatistics(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status) {
        
        // 这里应该根据当前商家ID过滤订单
        // 暂时返回示例数据
        Map<String, Object> response = new HashMap<>();
        response.put("orders", List.of());
        response.put("totalElements", 0);
        response.put("totalPages", 0);
        
        return ResponseEntity.ok(response);
    }

    @GetMapping("/merchant/customers/statistics")
    @Operation(summary = "获取商家客户统计")
    public ResponseEntity<Map<String, Object>> getMerchantCustomersStatistics(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("customers", List.of());
        response.put("totalElements", 0);
        response.put("totalPages", 0);
        
        return ResponseEntity.ok(response);
    }

    // ==================== 系统总体统计 ====================
    @GetMapping("/admin/statistics")
    @Operation(summary = "获取管理员统计数据")
    public ResponseEntity<Map<String, Object>> getAdminDashboard() {
        Map<String, Object> dashboard = new HashMap<>();
        
        // 订单统计
        LaundryOrderService.OrderStatistics orderStats = laundryOrderService.getOrderStatistics();
        dashboard.put("orderStatistics", Map.of(
            "total", orderStats.getTotalOrders(),
            "today", orderStats.getTodayOrders(),
            "pending", orderStats.getPendingOrders()
        ));
        
        // 财务统计
        BigDecimal totalIncome = incomeRepository.getTotalIncome();
        BigDecimal totalExpense = expenseRepository.getTotalExpense();
        LocalDateTime startOfDay2 = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime endOfDay2 = startOfDay2.plusDays(1);
        dashboard.put("financeStatistics", Map.of(
            "totalIncome", totalIncome != null ? totalIncome : BigDecimal.ZERO,
            "totalExpense", totalExpense != null ? totalExpense : BigDecimal.ZERO,
            "todayIncome", incomeRepository.getTodayIncome(startOfDay2, endOfDay2),
            "todayExpense", expenseRepository.getTodayExpense(startOfDay2, endOfDay2)
        ));
        
        // 用户统计
        List<Object[]> userRoleStats = userRepository.countByRole();
        List<Object[]> userStatusStats = userRepository.countByStatus();
        dashboard.put("userStatistics", Map.of(
            "total", userRepository.count(),
            "byRole", userRoleStats,
            "byStatus", userStatusStats
        ));
        
        // 设备统计
        List<Object[]> equipmentStatusStats = equipmentRepository.countByStatus();
        dashboard.put("equipmentStatistics", Map.of(
            "total", equipmentRepository.count(),
            "byStatus", equipmentStatusStats
        ));
        
        // 库存统计
        Double totalInventoryValue = inventoryRepository.getTotalInventoryValue();
        Long lowStockCount = inventoryRepository.countLowStockItems();
        dashboard.put("inventoryStatistics", Map.of(
            "totalValue", totalInventoryValue != null ? totalInventoryValue : 0.0,
            "lowStockCount", lowStockCount,
            "totalItems", inventoryRepository.count()
        ));
        
        return ResponseEntity.ok(dashboard);
    }
}
